<?php
/**
 * Created by PhpStorm.
 * Script Name: Minitester.php
 * Create: 2023/02/24 下午9:21
 * Description: 体验者管理
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use EasyOpen\Tencent\Client as TencentCli;
use EasyOpen\Tencent\Request\Mp\WxaBindTester;
use EasyOpen\Tencent\Request\Mp\WxaUnbindTester;
use plugin\wechat\app\model\MiniTester as TesterM;
use plugin\wechat\app\service\MiniTester as TesterService;
use plugin\wechat\app\TenantController;
use Support\Request;

class Minitester extends TenantController
{
    /**
     * @var TesterM
     */
    protected $model;
    /**
     * @var TencentCli
     */
    private $client;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new TesterM();
        $this->client = new TencentCli();
    }

    /**
     * 设置状态
     * @return \support\Response
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function setStatusPost(){
        if(request()->isPost()){
            $post_data = input('post.');
            $data = $this->model->where([$this->tenantWhere()])
                ->find($post_data['ids']);
            if(empty($data)){
                return $this->error('参数错误!');
            }
            $status = input('val', 0);
            if($status){
                $response = TesterService::testerUnbind($data);
            }else{
                $response = TesterService::testerAdd($data);
            }
            if(is_string($response)) {
                $this->model->update(['id' => $data['id'], 'status' => abs($status - 1)]);
                return $this->success('操作成功!');
            }else{
                return $this->error($response);
            }
        }
    }

    /**
     * 测试员列表
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request)
    {
        $mini_info = $request->miniInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['mini_id', '=', $mini_info['id']]
            ];
            !empty($post_data['search_key']) && $where[] = [
                'wechat_id|remark', 'like', '%' . $post_data['search_key'] . '%'
            ];
            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '根据微信号/备注搜索']
        ])
            ->addTopButton('addnew')
            ->addTableColumn(['title' => '微信号', 'field' => 'wechat_id',  'minWidth' => 100])
            ->addTableColumn(['title' => '备注', 'field' => 'remark', 'minWidth' => 100])
            ->addTableColumn(['title' => '绑定状态', 'field' => 'status', 'type' => 'switch', 'options' => [0 => '未绑定', 1 => '已绑定'], 'minWidth' => 100])
            ->addTableColumn(['title' => '最后操作时间', 'field' => 'update_time', 'minWidth' => 180]);

        return $builder->show();
    }

    /**
     * 新增体验者
     * @return mixed|\support\Response
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function add(){
        $mini_info = \request()->miniInfo;
        if(\request()->isPost()){
            $post_data = input('post.');
            $res = $this->validate($post_data, '\\plugin\\wechat\\app\\validate\\MiniTester');
            if($res !== true){
                return $this->error($res, '', ['token' => token()]);
            }

            if(is_string($response = TesterService::testerAdd($post_data))) {
                return $this->error($response, '', ['token' => token()]);
            }
            //数据入库
            $insert_data = [
                'company_id'   => $mini_info['company_id'],
                'mini_id'   => $mini_info['id'],
                'wechat_id' => $post_data['wechat_id'],
                'remark'    => $post_data['remark']
            ];
            $this->model->create($insert_data);
            return $this->success('添加成功');
        }
        if($this->model->where([
                $this->tenantWhere(),
                ['status','=', 1],
                ['mini_id','=', $mini_info['id']]
            ])->count() >= 30
        ){
            return $this->error('体验者人数最多只能添加30个!');
        }
        $builder = new FormBuilder();
        $builder->addFormItem('wechat_id', 'text', '微信号', '微信账号的微信号，不是昵称', [], 'required maxlength=60')
            ->addFormItem('remark', 'text', '备注', '此处建议写体验者的姓名', [], 'required maxlegnth=20');
        return $builder->show();
    }
}